<?php
/**
 * 小程序活动功能API
 * 处理活动查询、报名等功能
 */

require_once 'base.php';

class ActivityAPI extends MiniappBase {
    
    /**
     * 获取活动列表
     */
    public function getActivities() {
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 10);
        $status = $_GET['status'] ?? null;
        $category = $_GET['category'] ?? null;
        
        try {
            $sql = "SELECT id, title, description, category, activity_date, start_time, end_time,
                           max_participants, current_participants, registration_deadline,
                           location, status, featured_image, created_at
                    FROM activities 
                    WHERE 1=1";
            
            $params = [];
            
            // 只显示已发布的活动
            $sql .= " AND status IN ('published', 'registration_open', 'registration_closed', 'ongoing', 'completed')";
            
            if ($status) {
                $sql .= " AND status = ?";
                $params[] = $status;
            }
            
            if ($category) {
                $sql .= " AND category = ?";
                $params[] = $category;
            }
            
            $sql .= " ORDER BY activity_date DESC, created_at DESC 
                     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $activities = $this->db->fetchAll($sql, $params);
            
            // 获取总数
            $countSql = str_replace("SELECT id, title, description, category, activity_date, start_time, end_time, max_participants, current_participants, registration_deadline, location, status, featured_image, created_at", "SELECT COUNT(*) as total", $sql);
            $countSql = preg_replace('/ORDER BY.*LIMIT.*/', '', $countSql);
            $total = $this->db->fetchOne($countSql, $params)['total'];
            
            // 格式化数据并添加状态信息
            foreach ($activities as &$activity) {
                $activity['start_time'] = substr($activity['start_time'], 0, 5);
                $activity['end_time'] = substr($activity['end_time'], 0, 5);
                $activity['created_at'] = $this->formatTime($activity['created_at']);
                
                // 计算报名状态
                $now = time();
                $activityDate = strtotime($activity['activity_date']);
                $registrationDeadline = strtotime($activity['registration_deadline']);
                
                $activity['can_register'] = (
                    $activity['status'] === 'registration_open' &&
                    $now < $registrationDeadline &&
                    $activity['current_participants'] < $activity['max_participants']
                );
                
                $activity['remaining_spots'] = $activity['max_participants'] - $activity['current_participants'];
                $activity['is_full'] = $activity['current_participants'] >= $activity['max_participants'];
                $activity['is_past'] = $activityDate < $now;
                
                // 报名截止时间状态
                if ($now > $registrationDeadline) {
                    $activity['registration_status'] = 'expired';
                } elseif ($activity['is_full']) {
                    $activity['registration_status'] = 'full';
                } elseif ($activity['can_register']) {
                    $activity['registration_status'] = 'open';
                } else {
                    $activity['registration_status'] = 'closed';
                }
            }
            
            $this->success([
                'list' => $activities,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取活动列表失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取活动详情
     */
    public function getActivity($id) {
        if (empty($id)) {
            $this->error('缺少活动ID');
        }
        
        try {
            $sql = "SELECT * FROM activities WHERE id = ?";
            $activity = $this->db->fetchOne($sql, [$id]);
            
            if (!$activity) {
                $this->error('活动不存在', 404);
            }
            
            // 只显示已发布的活动
            if (!in_array($activity['status'], ['published', 'registration_open', 'registration_closed', 'ongoing', 'completed'])) {
                $this->error('活动不存在', 404);
            }
            
            // 格式化数据
            $activity['start_time'] = substr($activity['start_time'], 0, 5);
            $activity['end_time'] = substr($activity['end_time'], 0, 5);
            $activity['created_at'] = $this->formatTime($activity['created_at']);
            $activity['updated_at'] = $this->formatTime($activity['updated_at']);
            
            // 计算报名状态
            $now = time();
            $activityDate = strtotime($activity['activity_date']);
            $registrationDeadline = strtotime($activity['registration_deadline']);
            
            $activity['can_register'] = (
                $activity['status'] === 'registration_open' &&
                $now < $registrationDeadline &&
                $activity['current_participants'] < $activity['max_participants']
            );
            
            $activity['remaining_spots'] = $activity['max_participants'] - $activity['current_participants'];
            $activity['is_full'] = $activity['current_participants'] >= $activity['max_participants'];
            $activity['is_past'] = $activityDate < $now;
            
            // 报名截止时间状态
            if ($now > $registrationDeadline) {
                $activity['registration_status'] = 'expired';
            } elseif ($activity['is_full']) {
                $activity['registration_status'] = 'full';
            } elseif ($activity['can_register']) {
                $activity['registration_status'] = 'open';
            } else {
                $activity['registration_status'] = 'closed';
            }
            
            $this->success($activity);
            
        } catch (Exception $e) {
            $this->error('获取活动详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 报名参加活动
     */
    public function applyActivity($activityId) {
        $user = $this->getCurrentUser();
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (empty($activityId)) {
            $this->error('缺少活动ID');
        }
        
        // 验证必填字段
        $required = ['participant_name', 'participant_phone'];
        foreach ($required as $field) {
            if (empty($input[$field])) {
                $this->error("缺少必填字段: $field");
            }
        }
        
        try {
            // 检查活动是否存在
            $sql = "SELECT * FROM activities WHERE id = ?";
            $activity = $this->db->fetchOne($sql, [$activityId]);
            
            if (!$activity) {
                $this->error('活动不存在', 404);
            }
            
            // 检查活动状态
            if ($activity['status'] !== 'registration_open') {
                $this->error('活动未开放报名');
            }
            
            // 检查报名截止时间
            $now = time();
            $registrationDeadline = strtotime($activity['registration_deadline']);
            
            if ($now > $registrationDeadline) {
                $this->error('报名已截止');
            }
            
            // 检查是否已满员
            if ($activity['current_participants'] >= $activity['max_participants']) {
                $this->error('活动已满员');
            }
            
            // 检查用户是否已报名
            $existingSql = "SELECT id FROM activity_applications 
                           WHERE user_id = ? AND activity_id = ? AND status != 'cancelled'";
            $existing = $this->db->fetchOne($existingSql, [$user['id'], $activityId]);
            
            if ($existing) {
                $this->error('您已报名该活动');
            }
            
            // 生成申请号
            $applicationNo = 'A' . date('Ymd') . sprintf('%04d', rand(1000, 9999));
            
            // 创建报名记录
            $sql = "INSERT INTO activity_applications (
                        user_id, activity_id, participant_name, participant_phone, 
                        participant_email, id_card, emergency_contact, special_requirements,
                        application_no, status, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";
            
            $params = [
                $user['id'],
                $activityId,
                $input['participant_name'],
                $input['participant_phone'],
                $input['participant_email'] ?? '',
                $input['id_card'] ?? '',
                $input['emergency_contact'] ?? '',
                $input['special_requirements'] ?? '',
                $applicationNo
            ];
            
            $this->db->execute($sql, $params);
            $applicationId = $this->db->lastInsertId();
            
            // 更新活动参与人数
            $updateSql = "UPDATE activities 
                         SET current_participants = current_participants + 1,
                             updated_at = NOW()
                         WHERE id = ?";
            $this->db->execute($updateSql, [$activityId]);
            
            // 记录日志
            $this->logApi('apply_activity', [
                'user_id' => $user['id'],
                'activity_id' => $activityId,
                'application_id' => $applicationId
            ]);
            
            $this->success([
                'application_id' => $applicationId,
                'application_no' => $applicationNo,
                'status' => 'pending'
            ], '报名成功，请等待审核');
            
        } catch (Exception $e) {
            $this->error('报名失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户活动报名记录
     */
    public function getUserApplications() {
        $user = $this->getCurrentUser();
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 10);
        $status = $_GET['status'] ?? null;
        
        try {
            $sql = "SELECT aa.*, a.title, a.activity_date, a.start_time, a.end_time, a.location
                    FROM activity_applications aa
                    LEFT JOIN activities a ON aa.activity_id = a.id
                    WHERE aa.user_id = ?";
            
            $params = [$user['id']];
            
            if ($status) {
                $sql .= " AND aa.status = ?";
                $params[] = $status;
            }
            
            $sql .= " ORDER BY aa.created_at DESC 
                     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $applications = $this->db->fetchAll($sql, $params);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM activity_applications WHERE user_id = ?";
            $countParams = [$user['id']];
            
            if ($status) {
                $countSql .= " AND status = ?";
                $countParams[] = $status;
            }
            
            $total = $this->db->fetchOne($countSql, $countParams)['total'];
            
            // 格式化数据
            foreach ($applications as &$application) {
                $application['start_time'] = substr($application['start_time'], 0, 5);
                $application['end_time'] = substr($application['end_time'], 0, 5);
                $application['created_at'] = $this->formatTime($application['created_at']);
                $application['updated_at'] = $this->formatTime($application['updated_at']);
                
                // 判断活动是否已过期
                $activityDate = strtotime($application['activity_date']);
                $application['is_past'] = $activityDate < time();
            }
            
            $this->success([
                'list' => $applications,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取报名记录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取活动报名详情
     */
    public function getApplication($id) {
        $user = $this->getCurrentUser();
        
        if (empty($id)) {
            $this->error('缺少报名ID');
        }
        
        try {
            $sql = "SELECT aa.*, a.title, a.description, a.activity_date, a.start_time, 
                           a.end_time, a.location, a.status as activity_status,
                           au.username as reviewed_by_name
                    FROM activity_applications aa
                    LEFT JOIN activities a ON aa.activity_id = a.id
                    LEFT JOIN admin_users au ON aa.reviewed_by = au.id
                    WHERE aa.id = ? AND aa.user_id = ?";
            
            $application = $this->db->fetchOne($sql, [$id, $user['id']]);
            
            if (!$application) {
                $this->error('报名记录不存在', 404);
            }
            
            // 格式化数据
            $application['start_time'] = substr($application['start_time'], 0, 5);
            $application['end_time'] = substr($application['end_time'], 0, 5);
            $application['created_at'] = $this->formatTime($application['created_at']);
            $application['updated_at'] = $this->formatTime($application['updated_at']);
            $application['reviewed_at'] = $this->formatTime($application['reviewed_at']);
            
            // 判断活动是否已过期
            $activityDate = strtotime($application['activity_date']);
            $application['is_past'] = $activityDate < time();
            
            $this->success($application);
            
        } catch (Exception $e) {
            $this->error('获取报名详情失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 取消活动报名
     */
    public function cancelApplication($id) {
        $user = $this->getCurrentUser();
        
        if (empty($id)) {
            $this->error('缺少报名ID');
        }
        
        try {
            // 检查报名记录
            $sql = "SELECT aa.*, a.activity_date, a.registration_deadline
                    FROM activity_applications aa
                    LEFT JOIN activities a ON aa.activity_id = a.id
                    WHERE aa.id = ? AND aa.user_id = ?";
            
            $application = $this->db->fetchOne($sql, [$id, $user['id']]);
            
            if (!$application) {
                $this->error('报名记录不存在', 404);
            }
            
            // 检查状态
            if ($application['status'] === 'cancelled') {
                $this->error('报名已取消');
            }
            
            if ($application['status'] === 'completed') {
                $this->error('活动已完成，无法取消');
            }
            
            // 检查是否可以取消（活动开始前2小时可以取消）
            $activityDate = strtotime($application['activity_date']);
            $cancelDeadline = strtotime('-2 hours', $activityDate);
            
            if (time() > $cancelDeadline) {
                $this->error('活动开始前2小时内无法取消报名');
            }
            
            // 取消报名
            $sql = "UPDATE activity_applications 
                    SET status = 'cancelled', updated_at = NOW() 
                    WHERE id = ?";
            $this->db->execute($sql, [$id]);
            
            // 更新活动参与人数
            $updateSql = "UPDATE activities 
                         SET current_participants = current_participants - 1,
                             updated_at = NOW()
                         WHERE id = ?";
            $this->db->execute($updateSql, [$application['activity_id']]);
            
            // 记录日志
            $this->logApi('cancel_application', [
                'user_id' => $user['id'],
                'application_id' => $id
            ]);
            
            $this->success(null, '报名已取消');
            
        } catch (Exception $e) {
            $this->error('取消报名失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取活动分类
     */
    public function getCategories() {
        try {
            $sql = "SELECT DISTINCT category FROM activities 
                    WHERE status IN ('published', 'registration_open', 'registration_closed', 'ongoing', 'completed')
                    AND category IS NOT NULL AND category != ''
                    ORDER BY category";
            
            $categories = $this->db->fetchAll($sql);
            
            $this->success($categories);
            
        } catch (Exception $e) {
            $this->error('获取活动分类失败: ' . $e->getMessage());
        }
    }
}

// 处理请求
$activity = new ActivityAPI();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'list':
                $activity->getActivities();
                break;
            case 'detail':
                $activity->getActivity($_GET['id'] ?? '');
                break;
            case 'my_applications':
                $activity->getUserApplications();
                break;
            case 'application_detail':
                $activity->getApplication($_GET['id'] ?? '');
                break;
            case 'categories':
                $activity->getCategories();
                break;
            default:
                $activity->error('无效的操作');
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'apply':
                $activity->applyActivity($_GET['activity_id'] ?? '');
                break;
            default:
                $activity->error('无效的操作');
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'cancel':
                $activity->cancelApplication($_GET['id'] ?? '');
                break;
            default:
                $activity->error('无效的操作');
        }
        break;
        
    default:
        $activity->error('不支持的请求方法');
}
?>